

package org.wzq.learn;

import java.util.concurrent.CountDownLatch;

public class ThreadLocalDemo {

    static final int THREAD_NUM = 3;

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);
        Foo foo = new Foo();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                int randomInt = (int) Math.floor(Math.random() * 3 * 1000);
                try {
                    Thread.sleep(randomInt);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                foo.print();
                foo.bar.set(randomInt);
                foo.print();
                countDownLatch.countDown();
            }).start();
        }

        countDownLatch.await();
    }


    static class Foo {
        // 通常 ThreadLocal变量都用 static
        private ThreadLocal<Integer> bar = new ThreadLocal<Integer>() {
            @Override
            public Integer initialValue() {
                return 0;
            }
        };

        public void print() {
            System.out.printf("%s,%d\n", Thread.currentThread(), this.bar.get());
        }
    }
}
